from django import template
from django import forms
from django.http import HttpResponseRedirect
from django.contrib.contenttypes.models import ContentType
from pirate_sources.models import IMGSource, URLSource
from pirate_core.views import HttpRedirectException, namespace_get
from django.template import Library

from filetransfers.api import prepare_upload

from django.conf import settings

from customtags.decorators import block_decorator
register = template.Library()
block = block_decorator(register)

get_namespace = namespace_get('pp_source')

@block
def pp_get_sources(context, nodelist, *args, **kwargs):
    context.push()
    namespace = get_namespace(context)

    obj = kwargs.get('object',None)

    if obj:
        namespace['urlsource_list'] = URLSource.objects.filter(object_pk=obj.pk)
        namespace['imgsource_list'] = IMGSource.objects.filter(object_pk=obj.pk)
        namespace['model'] = URLSource
    output = nodelist.render(context)
    context.pop()

    return output 



@block
def pp_imgsource_form(context, nodelist, *args, **kwargs):
    '''
    This block tag can create or process forms eitfrom genericview.views import HttpRedirectException, namespace_gether to create or to modify arguments.
    Usage is as follows:

    {% pp_topic_form POST=request.POST path=request.path topic=pp_topic.topic root=some_topic %}
       Do stuff with {{ pp_source.form }}.
    {% endpp_topic_form %}
    '''
    context.push()
    namespace = get_namespace(context)

    POST  = kwargs.get('POST', None)
    FILE = kwargs.get('FILE',None)
    source = kwargs.get('source',None)
    obj = kwargs.get('object',None)
    user = kwargs.get('user',None)
    request = kwargs.get('request',None)

    if POST and POST.get("form_id") == "pp_imgsource_form":
        form = IMGSourceForm(POST,FILE) if source is None else IMGSourceForm(POST, FILE, instance=source)
        if form.is_valid(): 
            new_source = form.save(commit=False)
            new_source.user = user
            new_source.content_type = ContentType.objects.get_for_model(obj.__class__)
            new_source.object_pk = obj.pk
            #now create thumbnail
            new_source.thumbnail = '/thumb' + str(object_pk)

            new_source.save()
        path = obj.get_absolute_url()
        #raise HttpRedirectException(HttpResponseRedirect(path))
    else:
        view_url = obj.get_absolute_url()
        upload_url, upload_data = prepare_upload(request, view_url)
        form = IMGSourceForm() if source is None else IMGSourceForm(instance=source)
        namespace['upload_url'] = upload_url
        namespace['upload_data'] = upload_data
    namespace['imgform'] = form
    output = nodelist.render(context)
    context.pop()

    return output    
    
class IMGSourceForm(forms.ModelForm):

    def save(self, commit=True):
        new_source = super(IMGSourceForm, self).save(commit=commit)
        return new_source

    class Meta:
        model = IMGSource
        exclude = ('content_type','object_pk','content_object','user','thumbnail')

    form_id = forms.CharField(widget=forms.HiddenInput(), initial="pp_imgsource_form")


@block
def pp_urlsource_form(context, nodelist, *args, **kwargs):
    '''
    This block tag can create or process forms eitfrom genericview.views import HttpRedirectException, namespace_gether to create or to modify arguments.
    Usage is as follows:

    {% pp_topic_form POST=request.POST path=request.path topic=pp_topic.topic root=some_topic %}
       Do stuff with {{ pp_source.form }}.
    {% endpp_topic_form %}
    '''
    context.push()
    namespace = get_namespace(context)

    POST  = kwargs.get('POST', None)
    source = kwargs.get('source',None)
    obj = kwargs.get('object',None)
    user = kwargs.get('user',None)

   # print request
   # print "WTF?"

    if POST and POST.get("form_id") == "pp_urlsource_form":
        form = URLSourceForm(POST) if source is None else URLSourceForm(POST, instance=source)
        if form.is_valid(): 
            new_source = form.save(commit=False)
            new_source.user = user
            new_source.content_type = ContentType.objects.get_for_model(obj.__class__)
            new_source.object_pk = obj.pk
            new_source.content_object = obj
            new_source.save()
        else: namespace['errors'] = "Not a valide URL"
        #path = obj.get_absolute_url()
        #raise HttpRedirectException(HttpResponseRedirect(path))
    else:

        form = URLSourceForm() if source is None else URLSourceForm(instance=source)

    namespace['urlform'] = form
    output = nodelist.render(context)
    context.pop()

    return output    
    
class URLSourceForm(forms.ModelForm):

    def save(self, commit=True):
        new_source = super(URLSourceForm, self).save(commit=commit)
        return new_source

    class Meta:
        model = URLSource
        exclude = ('content_type','object_pk','content_object','user',)

    form_id = forms.CharField(widget=forms.HiddenInput(), initial="pp_urlsource_form")
